/* eslint-disable no-shadow */
import React, { Component } from 'react';
import Taro, { Config, getCurrentInstance } from '@tarojs/taro';
import { View, Input, ScrollView } from '@tarojs/components'
import StoreListView from '@/components/StoreListView'
import classnames from 'classnames'
import { debounce } from '@/utils'
import { hasPrevRoute } from '@/utils/global'
import { connect } from 'react-redux'
import { updateStore, initLocation } from '@/store/location/action'
import { allStore } from '@/api'
import cloneDeep from 'lodash/cloneDeep'
import './index.scss'

interface State {
  address: any
  tabIndex: number
  store: IStore | null
  loadLocation: boolean
  otfenStore: IStore[] | null
  nearStore: IStore[] | null
  reload: boolean
  keyWordStore: IStore[]
  allStoreList: IStore[]
}

@connect<any>(({ location, user }) => ({ location, user }), _dispatch => ({
  dispatchStore(params) {
    return _dispatch(updateStore(params))
  },
  dispatchLocation(params) {
    return _dispatch(initLocation(params))
  }
}))
export default class Index extends Component<any> {
  $instance = getCurrentInstance();
  constructor () {
    super(...arguments)
    this.state = {
      address: null,
      tabIndex: 1,
      store: null,
      loadLocation: false,
      otfenStore: null,
      nearStore: null,
      reload: false,
      keyWordStore: [],
      allStoreList: []
    }
  }
  state: State

  UNSAFE_componentWillMount() { }
  async componentDidMount() {
    this.addAllStore()
  }
  UNSAFE_componentWillReceiveProps(nextProps, nextContext) {


  }
  componentWillUnmount() { }
  componentDidShow() { }
  componentDidHide() { }
  componentDidCatchError() { }
  componentDidNotFound() { }

  // 当前门店数据

  private addAllStoreStatus = false
  private allStorePage: number = 1
  async addAllStore() {
    if (!this.addAllStoreStatus) {
      this.allStorePage++
      this.addAllStoreStatus = true
      await this.getAllStore()
      this.addAllStoreStatus = false
    }
  }
  // 全部门店
  getAllStore() {
    let paramsData = {
      userLongitude: 0,
      userLatitude: 0,
      query: {
        page: this.allStorePage
      }
    }
    // 如果链接携带分销信息 查询门店时需一起发送
    let { goodsDistributionId } = this.$instance.router.params
    if (goodsDistributionId) {
      paramsData.query.goodsDistributionId = goodsDistributionId
    }
    allStore(paramsData).then(res => {
      const data = res.data.data
			let fnData = []
			let transFnData = cloneDeep(data)
			transFnData.map((item)=>{
				if(!['000021', '000985', '000986'].includes(item.vendorCode)){ // 不能包含直营门店
					fnData.push(item)
				}
			})

      const { keyWordStore } = this.state
      if (keyWordStore.length) {
        this.setState({
          keyWordStore: [...keyWordStore, ...fnData]
        })
      } else {
        this.setState({
          keyWordStore: [...fnData]
        })
      }
    })
  }

  // 搜索
  searchLocation = debounce((e) => {
    const { value: keyword } = e.detail
    if (keyword) {
      let paramsData = {
        userLongitude: 0,
        userLatitude: 0,
        keyword,
        query: {}
      }
      // 如果链接携带分销信息 查询门店时需一起发送
      let { goodsDistributionId } = this.$instance.router.params
      if (goodsDistributionId) {
        paramsData.query.goodsDistributionId = goodsDistributionId
      }
      allStore(paramsData).then(res => {
        const data = res.data.data
				let fnData = []
				let transFnData = cloneDeep(data)
				transFnData.map((item)=>{
					if(!['000021', '000985', '000986'].includes(item.vendorCode)){ // 不能包含直营门店
						fnData.push(item)
					}
				})
        this.setState({
          keyWordStore: fnData
        })
      })
    } else {
      // this.setState({
      //   keyWordStore: []
      // })
			this.addAllStore()
    }
  }, 400)

  async changeStore(store?) {
    const { dispatchStore } = this.props
    await dispatchStore(store)
    this.setState({
      store
    }, () => {
      if (hasPrevRoute()) {
				let page = Taro.getCurrentPages()
				let prevpage = page[page.length - 2]
				if(prevpage.route == 'pages/store/index/index'){ // 需要特殊处理下，没能开启定位的时候，也能通过手动选择门店范文
					Taro.switchTab({ url: '/pages/tabbar/index/index' })
				}else{
					Taro.navigateBack()
				}
      } else {
        Taro.switchTab({ url: '/pages/tabbar/index/index' })
      }
    })
  }



  render() {
    const {keyWordStore } = this.state
    return   (
      <View className='store-index'>
					<View className='store-main vendorStore'>
						<View className='store-index-fixed'>
							<View className='import-keywords'><Input placeholder-class='placeholder' onInput={(e) => this.searchLocation(e)} className='ipt' placeholder='输入门店名称、地址或区域'></Input></View>
						</View>

						<ScrollView lowerThreshold={120} scrollY onScrollToLower={() => this.addAllStore()} className='otfen-store show'>
							 {
								 keyWordStore.length && (
									 <View className='otfen-list'>
										 <View className='sub-title'>可用门店</View>
										 {
											 keyWordStore.map(list => {
												 return <StoreListView handleEvent={this.changeStore.bind(this)} key={list.id} list={list} />
											 })
										 }
									 </View>
								 )
							 }
						 </ScrollView>
					</View>
      </View>
    )
  }
}
